package flyingpig.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Transaction;

import flyingpig.data.dao.ImageInfoHome;
import flyingpig.data.domain.ImageInfo;
import flyingpig.hibernate.HibernateUtil;

/**
 * Servlet implementation class UploadImage
 */
public class UploadImage extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UploadImage() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");

		PrintWriter out = response.getWriter();
		
		String cachedUrl = request.getParameter("cachedUrl");

		Integer imageId = 0;
		try {
			imageId = Integer.parseInt(request.getParameter("imageId"));
		} catch (Exception e) {
			out.println("imageId is wrong");
		}
		if (imageId <= 0) {
			return;
		}

		ImageInfoHome imageInfoHome = new ImageInfoHome();

		Transaction tx = HibernateUtil.getCurrentSession().beginTransaction();
		try {
			ImageInfo imageInfo = imageInfoHome.findById(imageId);
			if (imageInfo == null
					&& !imageInfo.getCacheState().equals("CACHING"))
				return;
			imageInfo.setCachedUrl(cachedUrl);
			imageInfo.setCacheState("CACHED");
			imageInfoHome.persist(imageInfo);
			tx.commit();

			out.println("success");
		} catch (HibernateException e) {
			tx.rollback();
			out.println("failed");
			e.printStackTrace();
		} finally {

			out.flush();
			out.close();
		}

	}

}
